package com.spark.market.common.redis;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author zwd
 * @date 2021/6/30
 * @email zwd@hhh.com
 */
@Component
@Aspect
public class RedisCacheOperateAspect {
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @AfterThrowing("@annotation(com.spark.market.common.redis.RedisCacheOperate)")
    public void afterThrowing(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RedisCacheOperate redisCacheOperate = signature.getMethod().getAnnotation(RedisCacheOperate.class);
        RedisAnnotationResolver redisAnnotationResolver = RedisAnnotationResolver.getInstance();
        Integer key = (Integer) redisAnnotationResolver.resolver(joinPoint, redisCacheOperate.key());
        Integer value = (Integer) redisAnnotationResolver.resolver(joinPoint, redisCacheOperate.value());
        String prefix = (String) redisAnnotationResolver.resolver(joinPoint, redisCacheOperate.prefix()) ;
        String method = (String) redisAnnotationResolver.resolver(joinPoint, redisCacheOperate.method().getType());
        String currentKey = "";
        if (StringUtils.hasLength(prefix)) {
            currentKey  = prefix + key;
        }else {
            currentKey = String.valueOf(key);
        }
        Integer res = redisTemplate.opsForValue().get(currentKey);
        if (res == null) {
            //记录日志
            throw new RuntimeException(key + ":不存在");
        }
        if (method.equals(RedisOperateEnum.ADD.getType())) {
            redisTemplate.opsForValue().increment(currentKey, value);
        }else if (method.equals(RedisOperateEnum.DECREASE.getType())){
            redisTemplate.opsForValue().increment(currentKey, value*-1);
        }
    }
}
